
//? 类
function Queue() {
    this.quene = [];
}

//? 放任务
Queue.prototype.task = function (time, callback) {
    this.quene.push({ time, callback });
    return this;
};
//? 开始执行
Queue.prototype.start = function () {
    const quene = this.quene;
    //? 这里为什么要这样？因为需要then来保证串行
    let result = Promise.resolve();

    quene.forEach((item) => {
        //? result = result.then 使其必须等待前面的resolve
        result = result.then(() => {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve(item.callback());
                }, item.time);
            });
        });
    });

    return result;
};

//test
new Queue()
    .task(1000, () => {
        console.log(1)
    })
    // 间隔是2s
    .task(2000, () => {
        console.log(2)
    })
    // 间隔是1s
    .task(1000, () => {
        console.log(3)
    })
    .start()
